﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace Blogical.Tools.BizTalkUndeployHelper
{
    class ProcessHelper : IDisposable
    {
        public static string OutPutMessage = null;
        public static string ErrorMessage = null;
        public void Execute(string fileName, string arguments, int waitForExitSeconds)
        {
            OutPutMessage = string.Format("Executing: {0} {1}\n", fileName, arguments);
            Process process = new Process();
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.FileName = fileName;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.Start();

            process.WaitForExit(waitForExitSeconds);

            if (process.HasExited == false)
                throw new TimeoutException("Timeout");

            process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived); process.BeginErrorReadLine();
            process.BeginOutputReadLine();
        }
        void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(e.Data);
        }
        void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
            {
                if (String.IsNullOrEmpty(ErrorMessage) && e.Data.ToLower().StartsWith("error"))
                    ErrorMessage = e.Data;
                else if (!String.IsNullOrEmpty(ErrorMessage))
                    ErrorMessage += "\n" + e.Data;
            }
            OutPutMessage += "\n" + e.Data;
        }

        #region IDisposable Members

        public void Dispose()
        {
            ErrorMessage = null;
            OutPutMessage = null;
        }

        #endregion
    }
}
